<template>
  <div class="container">
    <el-select
      v-model="planId"
      @change="planChangeEvent"
      placeholder="请选择计划"
      size="small"
    >
      <el-option
        v-for="item in planList"
        :key="item.planId"
        :label="item.planName"
        :value="item.planId"
      ></el-option>
    </el-select>
    <canvas id="canvas" width="3000" height="2080"></canvas>
    <!-- <canvas id="canvas" width="1366" height="768"></canvas> -->
  </div>
</template>

<script>
import {
  getManagerName,
  getProjectName,
  getProjectDetails,
  planSelect,
} from "@/api/project/plan.js";

export default {
  name: "TimeLine",
  data() {
    return {
      isShow: false,
      planId: "",
      planList: [],
      stageTime: [
        { txt: "试验试用系统阶段", time: "202111" },
        { txt: "第一代系统组网部署阶段", time: "202311" },
        { txt: "运行阶段", time: "" },
      ],
      managerNum: "",
      project: [],
      project_details: [],
      // managerNum: [
      //   { name: "one院", len: 1 },
      //   { name: "two院", len: 1 },
      // ],
      // project: [
      //   "折行折",
      //   "折行哈哈嘻嘻我",
      // ],
      // project_details: [
      //   [
      //     { is: 1, text: "扑街", date: "20210611" },
      //     { is: 0, text: "扑街", date: "20210727" },
      //   ],
      //   [
      //     { is: 0, text: "xxxxxxx", date: "20210611" },
      //     { is: 1, text: "mmmmmmm", date: "20210727" },
      //   ]
      // ]
    };
  },
  methods: {
    //#region
    // printAtWordWrap(d, x, y, lineHeight, fitWidth) {
    //   var canvas = document.getElementById("canvas");
    //   var context = canvas.getContext("2d"); //得到绘图的上下文环境
    //   var text = d + '';
    //   console.log(text);
    //   fitWidth = fitWidth || 0;
    //   if (fitWidth <= 0) {
    //     context.fillText(text, x, y);
    //     return;
    //   }
    //   var words = text.split('');
    //   // var words = text + ''.split('\n');
    //   // var lines = project[index] + ''.split('\n');
    //   console.log(words);
    //   var currentLine = 0;
    //   var idx = 1;
    //   while (words.length > 0 && idx <= words.length) {
    //     var str = words.slice(0, idx).join(' ');
    //     var w = context.measureText(str).width;
    //     if (w > fitWidth) {
    //       context.moveTo(20, y)
    //       if (idx == 1) {
    //         idx = 2;
    //       }
    //       if()
    //       console.log(words.slice(0, idx - 1));
    //       context.fillText(words.slice(0, idx - 1).join(' '), x, y + (lineHeight * currentLine));
    //       currentLine++;
    //       words = words.splice(idx - 1);
    //       idx = 1;
    //     }
    //     else { idx++; }
    //   }
    //   if (idx > 0)
    //     context.fillText(words.join(' '), x, y + (lineHeight * currentLine));
    // },
    planChangeEvent(value) {
      this.isShow = !this.isShow;
      var canvas = document.getElementById("canvas");
      let context = canvas.getContext("2d"); //得到绘图的上下文环境
      let w = canvas.width;
      let h = canvas.height;
      context.clearRect(0, 0, w, h);
      this.getManager(value).then((response) => {
        this.managerNum = response.data;
        this.getProject(value).then((response) => {
          this.project = response.data;
          this.getDetails(value).then((response) => {
            this.project_details = response.data;
            this.drawChart();
          });
        });
      });
    },
    planSelect() {
      planSelect().then((response) => {
        this.planList = response.rows;
        console.log(this.planList);
      });
    },
    getManager(planId) {
      return getManagerName(planId);
    },
    getProject(planId) {
      return getProjectName(planId);
    },
    getDetails(planId) {
      return getProjectDetails(planId);
    },
    //阶段线
    headLine(context, x, y, headLineHeight, width, rangeLength) {
      context.beginPath();
      context.moveTo(x, y - headLineHeight);
      context.lineTo(x + width * rangeLength, y - headLineHeight);
      context.moveTo(x, y - headLineHeight * 2);
      context.lineTo(x + width * rangeLength, y - headLineHeight * 2);

      context.moveTo(x, y - headLineHeight * 2);
      context.lineTo(x, y - headLineHeight);
      context.moveTo(x + width * rangeLength, y - headLineHeight * 2);
      context.lineTo(x + width * rangeLength, y - headLineHeight);
      context.stroke();
      context.closePath();
      for (var i = 0; i < this.stageTime.length - 1; i++) {
        context.beginPath();
        context.font = "12px sans-serif";
        context.moveTo(
          x + ((width * rangeLength) / 3) * (i + 1),
          y - headLineHeight * 2
        );
        context.fillText(
          this.stageTime[i].txt,
          x + ((width * rangeLength) / 3) * i + (width * rangeLength) / 3 / 2,
          y - headLineHeight - headLineHeight / 2
        );
        context.lineTo(
          x + ((width * rangeLength) / 3) * (i + 1),
          y - headLineHeight
        );
        context.stroke();
        context.closePath();
      }
      context.beginPath();
      context.fillText(
        this.stageTime[i].txt,
        x + ((width * rangeLength) / 3) * i + (width * rangeLength) / 3 / 2,
        y - headLineHeight - headLineHeight / 2
      );
      context.font = "12px sans-serif";
      context.stroke();
      context.closePath();
    },
    //画点
    drawDot(context, x, y, lineWidth) {
      context.beginPath();
      context.lineCap = "round";
      context.lineWidth = lineWidth;
      context.strokeStyle = "black";
      context.moveTo(x, y);
      context.lineTo(x, y);
      context.font = "12px 微软雅黑";
      context.textAlign = "center";
      context.textBaseline = "top";
      context.stroke();
      context.closePath();
    },

    //画星
    drawStar(context, r, x, y) {
      context.lineWidth = 5;
      context.beginPath();
      var dit = (Math.PI * 4) / 5;
      var sin = Math.sin(0) * r + y;
      var cos = Math.cos(0) * r + x;
      context.moveTo(cos, sin);
      for (var i = 0; i < 5; i++) {
        var tempDit = dit * i;
        sin = Math.sin(tempDit) * r + y;
        cos = Math.cos(tempDit) * r + x;
        context.lineTo(cos, sin);
      }
      context.closePath();
      context.strokeStyle = "red";
      context.fill();
      context.stroke();
      context.closePath();
    },

    //虚线
    dottedLine(context, x, y, projectNum, projectHeight) {
      context.beginPath();
      context.setLineDash([5]);
      context.moveTo(x, y);
      context.lineTo(x, y + projectHeight * projectNum);
      context.lineWidth = 2;
      context.strokeStyle = "rgb(116,63,73)";
      context.stroke();
      context.setLineDash([]);
      context.closePath();
    },

    getRange(start_year, end_year) {
      var list = [];
      let year_start = parseInt(start_year.substring(0, 4));
      let month_start = parseInt(start_year.substring(4));
      let year_end = parseInt(end_year.substring(0, 4));
      let month_end = parseInt(end_year.substring(4));
      list.push({ year: year_start, is: 1 });
      let number = month_start + 1;
      let year = year_start;
      while (true) {
        if (year == year_end && month_end == number) {
          list.push({ year: number, is: 0 });
          break;
        }
        if (number <= 12) {
          if (number == 1) {
            list.push({ year: year, is: 1 });
          } else {
            list.push({ year: number, is: 0 });
          }
          number += 1;
        }
        if (number == 13) {
          number = 1;
          year += 1;
        }
      }
      return list;
    },

    //时间限制
    yearLine(
      ratio,
      context,
      range,
      project_num,
      project_height,
      first_space,
      end_space,
      x,
      y,
      width,
      height,
      lineWidth
    ) {
      /**
       * 竖线
       */
      context.beginPath();
      for (var i = 0; i < range.length; i++) {
        let year = range[i].year;
        let is = range[i].is;
        let write_x = x + i * width;
        context.font = "10px";
        if (is == 0) {
          if (i == range.length - 1) {
            context.moveTo(write_x, y - height);
            context.lineTo(write_x, y + project_num * project_height);
          } else {
            context.moveTo(write_x, y);
            context.lineTo(write_x, y - height);
          }
          // context.fillText(year, write_x, y - height - 20);
          context.fillText(year, write_x, 185);
        } else if (is == 1) {
          context.moveTo(write_x, y - height);
          if (i == 0) {
            context.lineTo(write_x, y + project_num * project_height);
          } else {
            context.lineTo(write_x, y + height);
          }
          context.font = "12px sans-serif";
          context.textBaseline = "center";
          // context.font = 16 * ratio + 'px sans-serif';
          context.fillText(year, write_x - width / 2, 180);
          // context.fillText(year, write_x - width / 2, y - height - 20);
        }
      }
      context.strokeStyle = "black";
      context.lineWidth = lineWidth;
      context.stroke();
      context.closePath();
      /**
       * 横线
       */
      context.beginPath();
      context.moveTo(x - first_space, y);
      context.lineTo(x + (range.length - 1) * width + end_space, y);
      context.lineWidth = lineWidth;
      context.strokeStyle = "black";
      context.stroke();
      context.closePath();
    },

    yearLineEnd(
      context,
      range,
      project_num,
      project_height,
      first_space,
      end_space,
      x,
      y,
      width,
      height,
      lineWidth
    ) {
      /**
       * 竖线
       */
      context.beginPath();
      for (let ele in range) {
        let year = range[ele].year;
        let is = range[ele].is;
        let write_x = x + ele * width;
        if (is == 0) {
          context.moveTo(write_x, y);
          context.lineTo(write_x, y - height);
          context.fillText(year, write_x, y + 5);
        } else if (is == 1) {
          context.moveTo(write_x, y - height);
          context.lineTo(write_x, y + height);
          context.font = "12px sans-serif";
          context.textBaseline = "center";
          // context.font = 16 * ratio + 'px sans-serif';
          context.fillText(year, write_x, y + 20);
        }
      }
      context.strokeStyle = "black";
      context.lineWidth = lineWidth;
      context.stroke();
      context.closePath();
      /**
       * 横线
       */
      context.beginPath();
      context.moveTo(x - first_space, y);
      context.lineTo(x + (range.length - 1) * width + end_space, y);
      context.lineWidth = lineWidth;
      context.strokeStyle = "black";
      context.stroke();
      context.closePath();
    },

    //垂直线
    verticalLine(context, x, y, projectNum, projectHeight, lineWidth) {
      context.beginPath();
      context.moveTo(x, y);
      context.lineTo(x, y + projectNum * projectHeight);
      context.lineWidth = lineWidth;
      context.strokeStyle = "black";
      context.stroke();
      context.closePath();
    },

    //水平线
    horizontalLine(
      context,
      x,
      y,
      projectNum,
      projectHeight,
      rangLength,
      width,
      firstSpace,
      lineWidth
    ) {
      context.beginPath();
      context.moveTo(x, y + projectNum * projectHeight);
      context.lineTo(
        x + (rangLength - 1) * width + firstSpace,
        y + projectNum * projectHeight
      );
      context.lineWidth = lineWidth;
      context.strokeStyle = "black";
      context.stroke();
      context.closePath();
    },

    //各类项目机构的显示
    manager(
      context,
      x,
      y,
      managerNum,
      projectHeight,
      firstSpace,
      lineWidth,
      ratio
    ) {
      let move_y = y;
      for (let index in managerNum) {
        context.beginPath();
        let managerNumElement = managerNum[index];
        let name = managerNumElement.name;
        let allHeight = managerNumElement.len * projectHeight;
        context.moveTo(x - firstSpace, move_y + allHeight);
        context.lineTo(x - firstSpace / 2, move_y + allHeight);
        context.lineWidth = lineWidth;
        context.strokeStyle = "black";
        context.font = "12px sans-serif";
        context.textBaseline = "center";
        // context.font = 16 * ratio + 'px sans-serif';
        context.fillTextVertical(
          name,
          x - firstSpace / 2 - firstSpace / 4,
          move_y + allHeight / 2
        );
        move_y += allHeight;
        context.stroke();
        context.closePath();
      }
    },

    manager_end(
      context,
      x,
      y,
      managerNum,
      projectHeight,
      endSpace,
      lineWidth,
      ratio,
      firstSpace
    ) {
      let move_y = y;
      for (let index in managerNum) {
        context.beginPath();
        let managerNumElement = managerNum[index];
        let name = managerNumElement.name;
        let allHeight = managerNumElement.len * projectHeight;
        context.moveTo(x + endSpace / 2, move_y + allHeight);
        context.lineTo(x + endSpace, move_y + allHeight);
        context.lineWidth = lineWidth;
        context.strokeStyle = "black";
        context.font = "12px sans-serif";
        context.textBaseline = "center";
        // context.font = 16 * ratio + 'px sans-serif';
        context.fillTextVertical(
          name,
          x + endSpace / 2 + endSpace / 4,
          move_y + allHeight / 2
        );
        move_y += allHeight;
        context.stroke();
        context.closePath();
      }
    },

    //项目
    mangerProject(
      context,
      x,
      y,
      firstSpace,
      projectHeight,
      project,
      width,
      rangLength
    ) {
      for (let index in project) {
        context.beginPath();
        let allHeight = y + projectHeight * (parseInt(index) + 1);
        context.moveTo(x - firstSpace / 2, allHeight);
        context.lineTo(x + width * rangLength, allHeight);
        context.font = "12px sans-serif";
        context.textBaseline = "left";
        if (project[index].length > 5) {
          var times = project[index].length / 2
          for (var i = 0; i < parseInt(times); i++) {
            // debugger
            var t = project[index].substring(i * 2, 2 * (i + 1))
            console.log(t)
            context.fillText(t, x - 40,
              allHeight - projectHeight / 2 + 20 * i)
          }
          if (!Number.isInteger(times)) {
            var t = project[index].substring(2 * parseInt(times))

            context.fillText(t, x - 40,
              allHeight - projectHeight / 2 + 20 * (times - 1) + 10)
          }
        } else {
          context.fillTextVertical(
            project[index],
            x - firstSpace / 2 + firstSpace / 4,
            allHeight - projectHeight / 2
          );
        }

        // this.printAt(project[index] + '', x - firstSpace / 2 + firstSpace / 4 - 15, allHeight - projectHeight / 2, 2, 100)
        // this.printAtWordWrap(project[index] + '', x - firstSpace / 2 + firstSpace / 4 - 15, allHeight - projectHeight / 2, 200, 200);
        // var lineheight = 10;
        // var lines = project[index].split('\n');
        // console.log(lines);
        // for (var i = 0; i < lines.length; i++)
        //   console.log(lines[i]);
        // context.fillText(lines[i], x - firstSpace / 2 + firstSpace / 4, allHeight - projectHeight / 2 + (i * lineheight));

        context.stroke();
        context.closePath();
      }
    },
    mangerProjectEnd(context, x, y, endSpace, projectHeight, project, ratio) {
      for (let index in project) {
        context.beginPath();
        let allHeight = y + projectHeight * (parseInt(index) + 1);
        context.moveTo(x + endSpace / 2, allHeight);
        context.lineTo(x, allHeight);
        context.font = "12px Arial";
        context.textBaseline = "center";
        // context.font = 16 * ratio + 'px sans-serif';
        context.fillTextVertical(
          project[index],
          x + endSpace / 2 - endSpace / 4,
          allHeight - projectHeight / 2
        );
        context.stroke();
        context.closePath();
      }
    },

    //画文字
    drawText(context, t, x, y, w, ratio) {
      var chr = t.split("");
      var temp = "";
      var row = [];

      context.font = "12px sans-serif";
      context.textBaseline = "center";
      // context.font = 15 * ratio + 'px sans-serif';

      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width < w) {
        } else {
          row.push(temp);
          temp = "";
        }
        temp += chr[a];
      }

      row.push(temp);

      for (var b = 0; b < row.length; b++) {
        context.fillText(row[b], x, y + (b + 1) * 20);
      }
    },

    //画数据
    drawData(
      context,
      x,
      y,
      width,
      projectNum,
      projectHeight,
      rangeLength,
      project_details,
      ratio
    ) {
      for (let i = 0; i < projectNum; i++) {
        context.beginPath();
        context.moveTo(x, y + (i + 1) * projectHeight - projectHeight / 2);
        context.lineTo(
          x + width * (rangeLength - 1),
          y + (i + 1) * projectHeight - projectHeight / 2
        );
        context.lineWidth = 2;
        context.strokeStyle = "rgb(26,125,211)";
        context.stroke();
        context.closePath();
        let projectDetail = project_details[i];
        for (let j = 0; j < projectDetail.length; j++) {
          let s = projectDetail[j].date.substring(8);

          if (projectDetail[j].is == undefined) {
          } else {
            let x_x = x + (width * (j) + (width * parseInt(s)) / 31);
            let y_y = y + (i + 1) * projectHeight - projectHeight / 2;
            if (projectDetail[j].is == 1) {
              this.drawStar(context, 5, x_x, y_y);
              this.dottedLine(context, x_x, y, projectNum, projectHeight);
            } else {
              this.drawDot(
                context,
                x_x,
                y + (i + 1) * projectHeight - projectHeight / 2,
                10
              );
            }

            this.drawText(context, projectDetail[j].text, x_x, y_y, 80, ratio);
          }
        }
      }
    },
    drawChart() {
      window.CanvasRenderingContext2D.prototype.fillTextVertical = function (
        text,
        x,
        y
      ) {
        var context = this;
        var arrText = text.split("");
        var arrWidth = arrText.map(function (letter) {
          return context.measureText(letter).width;
        });
        var align = context.textAlign;
        var baseline = context.textBaseline;
        if (align == "left") {
          x = x + Math.max.apply(null, arrWidth) / 2;
        } else if (align == "right") {
          x = x - Math.max.apply(null, arrWidth) / 2;
        }
        if (
          baseline == "bottom" ||
          baseline == "alphabetic" ||
          baseline == "ideographic"
        ) {
          y = y - arrWidth[0] / 2;
        } else if (baseline == "top" || baseline == "hanging") {
          y = y + arrWidth[0] / 2;
        }
        context.textAlign = "center";
        context.textBaseline = "middle";
        // 开始逐字绘制
        arrText.forEach(function (letter, index) {
          // 确定下一个字符的纵坐标位置
          var letterWidth = arrWidth[index];
          // 是否需要旋转判断
          var code = letter.charCodeAt(0);
          if (code <= 256) {
            context.translate(x, y);
            // 英文字符，旋转90°
            context.rotate((90 * Math.PI) / 180);
            context.translate(-x, -y);
          } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
            // y修正
            y = y + arrWidth[index - 1] / 2;
          }
          context.fillText(letter, x, y);
          // 旋转坐标系还原成初始态
          context.setTransform(1, 0, 0, 1, 0, 0);
          // 确定下一个字符的纵坐标位置
          var letterWidth = arrWidth[index];
          y = y + letterWidth;
        });
        // 水平垂直对齐方式还原
        context.textAlign = align;
        context.textBaseline = baseline;
      };

      let range = this.getRange("202110", "202606");
      // 日期长度
      let rangeLength = range.length;
      var canvas = document.getElementById("canvas");
      let context = canvas.getContext("2d"); //得到绘图的上下文环境

      var devicePixelRatio = window.devicePixelRatio || 1;
      var backingStoreRatio =
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio ||
        1;
      var ratio = devicePixelRatio / backingStoreRatio;

      var oldWidth = canvas.width;
      var oldHeight = canvas.height;

      canvas.width = oldWidth * ratio;
      canvas.height = oldHeight * ratio;

      canvas.style.width = oldWidth + "px";
      canvas.style.height = oldHeight + "px";

      //所有项目数
      let projectNum = this.project.length;
      //每一个项目高度
      let projectHeight = 150;
      //前置宽度
      let firstSpace = 100;
      let endSpace = 120;
      //x 坐标
      let x = 100;
      //y坐标
      let y = 200;
      // 日期间隔的宽度
      let width = 30;
      //年的高度
      let height = 10;
      //线宽
      let lineWidth = 2;

      this.headLine(context, x, y, 35, width, rangeLength);
      this.yearLine(
        ratio,
        context,
        range,
        projectNum,
        projectHeight,
        firstSpace,
        endSpace,
        x,
        y,
        width,
        height,
        lineWidth
      );
      this.verticalLine(
        context,
        x - firstSpace,
        y,
        projectNum,
        projectHeight,
        lineWidth
      );
      this.verticalLine(
        context,
        x - firstSpace / 2,
        y,
        projectNum,
        projectHeight,
        lineWidth
      );
      this.horizontalLine(
        context,
        x - firstSpace,
        y,
        projectNum,
        projectHeight,
        range.length,
        width,
        firstSpace,
        lineWidth
      );
      this.manager(
        context,
        x,
        y,
        this.managerNum,
        projectHeight,
        firstSpace,
        lineWidth,
        ratio
      );
      this.mangerProject(
        context,
        x,
        y,
        firstSpace,
        projectHeight,
        this.project,
        width,
        rangeLength
      );
      this.mangerProjectEnd(
        context,
        x + width * (rangeLength - 1),
        y,
        endSpace,
        projectHeight,
        this.project,
        ratio
      );
      this.verticalLine(
        context,
        x + width * (rangeLength - 1) + endSpace / 2,
        y,
        projectNum,
        projectHeight,
        lineWidth
      );
      this.manager_end(
        context,
        x + width * (rangeLength - 1),
        y,
        this.managerNum,
        projectHeight,
        endSpace,
        lineWidth,
        ratio,
        firstSpace
      );
      this.verticalLine(
        context,
        x + width * (rangeLength - 1) + endSpace,
        y,
        projectNum,
        projectHeight,
        lineWidth
      );
      this.drawData(
        context,
        x,
        y,
        width,
        projectNum,
        projectHeight,
        rangeLength,
        this.project_details,
        ratio
      );
      this.yearLineEnd(
        context,
        range,
        projectNum,
        projectHeight,
        firstSpace,
        endSpace,
        x,
        y + projectHeight * projectNum,
        width,
        height,
        lineWidth
      );
    },
    //#endregion
  },
  mounted() {
    this.planSelect();
    // this.drawChart();
  },
};
</script>

<style lang='scss' scoped>
.container {
  background-color: #fff;
  width: 100%;
  height: 100%;
  #canvas {
    border: 1px solid #aaa;
    text-align: center;
    letter-pacing: 5px;
  }
}
</style>